<template>
<div>
    <ylheader :title="'发现'"></ylheader>
    <!--<div class="all-hot-title" >精选推荐</div>-->
    <div class="contanier">
       <div class="loadmore-container" ref="sayWrapper" >
      <div class="loadmore-ul" >
         <div class="myquanzi">
          <div class="toptitle">
            <p>我的圈子</p>
            <div class="findquanzi" @click="jump">发现圈子 ▶</div>
          </div>
          <div class="menuContainer" ref="menuWrap">
                <ul class="quanList" >
            <li v-for="(item,index) in list" :key="index" @click="gotodetail(item.id)">
              <img :src=item.pic>
              <p>{{item.name}}</p>
            </li>
          </ul>
          </div>
        </div>
          <ul >
            <li style="background-color: white;margin-bottom: .2rem" v-for="(item,index) in commentlist" :key="index">
              <hotheader :commentindex="index" :type="1" :nickname="item.nickName" :saytime="item.gmtCreate" :avatarimg="item.headImg" @topiccommentdetail="tosaycomdet" :place="item.park" :userType="item.userType" :isTalent="item.isTalent" :pendantType="item.pendantType" :pendantPicUrl="item.headImg"></hotheader>
              <commentbody :commentindex="index" :commenttype="null" :piclength="changeStrtoArr(item.pics).length" @replycomment="tosaycomdet" :circleid="item.circleId"  :circlename="item.name" :commenttext="item.content"  :picarray="changeStrtoArr(item.pics)" @showImg="popupImg"></commentbody>
              <div style="border-bottom: 1px solid #f5f5f5;">
                <div v-for="(each,idx) in item.circleDiscussCommentList" :key="idx" style="padding: 0.1rem 0.3rem;">
                  <div>
                    <!--<span style="color: #3fa7fb;">{{each.nickName}}：</span>-->
                    <span style="color: #3fa7fb;">{{each.nickName}}：<i v-if="each.beCircleDiscussCommentUserId>0" style="color:red">@{{each.beNickName}}</i></span>

                    <span>{{each.content}}</span>
                  </div>
                  <div style="display: flex; flex-wrap: wrap; margin: 0.2rem 0 0 -0.15rem;" v-if="each.pics">
                    <img v-for="(one,id) in (each.pics.split(','))" :key="id" @click="popupImg(selectimg(each),id)" v-lazy.container ="one" style="width: 2.2rem; height: 1.7rem; margin-left: 0.15rem;" />

                  </div>
                  <!-- <mt-popup
                  class="popImg"
                    v-model="popupVisible"
                    popup-transition="popup-fade"
                    :modal="true"
                  >
                    <img :src="popImg" >
                  </mt-popup> -->
                </div>
                <div style="color: #3fa7fb; padding: 0.1rem 0.3rem 0.2rem 0.3rem;" v-if="item.commentNum > 2" @click="saycomment(item)">共{{item.commentNum}}条回复 ></div>
              </div>
              <thubm-up :topiccommentnum="item.commentNum" :thumbupnum="item.likeNum" :commentindex="index" :isup="item.isLike" @thumbup="saythumbup" @commentsvgg="saycomment(item)"></thubm-up>
            </li>
          </ul>
      </div>
    </div>
    </div>
    <transition name="fade">
     <div class="modal-img" v-if="popupVisible" @click="popupVisible=false">
       <mt-swipe :auto="100000" style="width: 100%;height: 100vh;position:relative;"
       :continuous="false" 
        :defaultIndex="swiperIndex" :showIndicators="false" >
          <mt-swipe-item v-for="(item,index) in popImg" :key="index" style="height:100vh" >
            <img v-lazy="item" class="swiper-img" />
          </mt-swipe-item>
        </mt-swipe>
         <!-- <swiper :options="swiperOption" ref="mySwiperOne" style="width: 100%;height: 100vh;">
            <swiper-slide class="swiper-slide" v-for="(item,index) in popImg" :key="index">
                <img v-lazy="item"/>
            </swiper-slide>
        </swiper> -->
      <!-- <img :src="popImg" alt=""> -->
    </div>
  </transition>
  
    <indexnavigation></indexnavigation>
</div>
</template>
<script>
import ylheader from "src/components/yl-header.vue";
import indexnavigation from "src/components/index/indexnavigation.vue";
import hotheader from "src/components/allhot-header.vue";
import commentbody from "src/components/comment-detail-body.vue";
import thubmUp from "src/components/thumb-up.vue";
import { Navbar, TabItem,Indicator} from "mint-ui";
import BScroll from 'better-scroll'
import api from "src/api/index";
export default {
  name:"discovery",
  data(){
    return {
       list:[],
       page: 1,
       mypage:1,
       totalPage: 0,
       swiperIndex:0,
       moveX:0,
      commentlist: [],
      is_r:false,
       listnodata:false,
      popupVisible:false,
      popImg:'',
      swiperOption: {
        slidesPerView: 1,
      },
    }
  },
  components:{
    ylheader,
    api,
    indexnavigation,
    hotheader,
    commentbody,
    thubmUp,
  },
   computed: {
    swiperOne () {
      return this.$refs.mySwiperOne.swiper;//轮播 
    }
  },
  created(){
    Indicator.open("加载中")
      this.queryDiscovery();
  },
  mounted(){
    this.init();
  },
  methods:{
    // 整理图片为数组
    selectimg(imgarray,index){
      return imgarray.pics.split(',')
    },
    //显示图片
    popupImg(data,index){
      this.swiperIndex = index
      if(typeof data == 'string'){
        data = data.split(',')
      }
       //console.log(data,index)
      this.popImg = data;
      this.popupVisible = true;
      // console.log(this.swiperOne)
      // this.swiperOne.slideTo(index)
    },
    changeItem(v){
      let html = `<a @click=gotodetail(${v.circleId})>#${v.name}#</a>${v.content}`;
      return html;
    },
    gotodetail(id){
      this.$router.push({path:'discoveryDetails',query:{id:id}})
    },
    changeStrtoArr(str){
      if(!str) return false;
      let strArr = str.split(',');
      let newArr = [];
      for(let i=0; i<strArr.length;i++){
        newArr.push({'src':strArr[i]})
      }
      return newArr
    },
    jump(){
      this.$router.push('/findDiscovery')
    },
    saythumbup(data) {
      const params = {
        circleId: this.commentlist[data.commentindex].circleId,
        circleDiscussId: this.commentlist[data.commentindex].id
      };
      if (this.commentlist[data.commentindex].isLike == 0) {
        api.Querycirlethumbup(params).then(res => {
          if (res.success) {
            // this.$util.saveFootPrint({actType:9,typeValue:this.commentlist[data.commentindex].saysId});//用户轨迹
            this.commentlist[data.commentindex].isLike = 1;
            this.commentlist[data.commentindex].likes = res.data;
            //更新说说缓存数据
            let sayObj = JSON.stringify({
              commentlist: this.commentlist,
              totalPage: this.totalPage,
              hasmore: this.hasmore,
              pageone: this.pageone,
              pagetwo: this.pagetwo,
              mypage: this.mypage,
              timeorhot: this.timeorhot
            });
            localStorage.sayStorage = sayObj;
            this.initDiscuss();

          } else {
            this.$toast("点赞失败");
          }
        });
      } else if (this.commentlist[data.commentindex].isLike == 1) {
        api.queryDiscoverylikecancel(params).then(res => {
          if (res.success) {
            this.commentlist[data.commentindex].isLike = 0;
            this.commentlist[data.commentindex].likes = res.data;
            //更新说说缓存数据
            let sayObj = JSON.stringify({
              commentlist: this.commentlist,
              totalPage: this.totalPage,
              hasmore: this.hasmore,
              pageone: this.pageone,
              pagetwo: this.pagetwo,
              mypage: this.mypage,
              timeorhot: this.timeorhot
            });
            localStorage.sayStorage = sayObj;
            this.initDiscuss();

          } else {
            this.$toast("取消点赞失败");
          }
        });
      }
    },
    thumbup(data) {
      const params = {
        saysId: this.commentlist[data.commentindex].saysId,
        createSaysUserId: this.commentlist[data.commentindex].userId
      };
      if (this.commentlist[data.commentindex].isLike == 0) {
        api.Querycirlethumbup(params).then(res => {
          if (res.success) {
            // this.$util.saveFootPrint({actType:9,typeValue:this.commentlist[data.commentindex].saysId});//用户轨迹
            this.commentlist[data.commentindex].isLike = 1;
            this.commentlist[data.commentindex].likes = res.data;
            //更新说说缓存数据
            let sayObj = JSON.stringify({
              commentlist: this.commentlist,
              totalPage: this.totalPage,
              hasmore: this.hasmore,
              pageone: this.pageone,
              pagetwo: this.pagetwo,
              mypage: this.mypage,
              timeorhot: this.timeorhot
            });
            localStorage.sayStorage = sayObj;
            this.initDiscuss();

          } else {
            this.$toast("点赞失败");
          }
        });
      } else if (this.commentlist[data.commentindex].isLike == 1) {
        api.queryDiscoverylikecancel(params).then(res => {
          if (res.success) {
            this.initDiscuss()
            this.commentlist[data.commentindex].isLike = 0;
            this.commentlist[data.commentindex].likes = res.data;
            //更新说说缓存数据
            let sayObj = JSON.stringify({
              commentlist: this.commentlist,
              totalPage: this.totalPage,
              hasmore: this.hasmore,
              pageone: this.pageone,
              pagetwo: this.pagetwo,
              mypage: this.mypage,
              timeorhot: this.timeorhot
            });
            localStorage.sayStorage = sayObj;
          } else {
            this.$toast("取消点赞失败");
          }
        });
      }
    },
    saycomment(data) {
      // console.log(data,this.commentlist)
      localStorage.turnCount = "detail2say";
      this.getTransformState();

    /*  let commentList0 = JSON.stringify(this.commentList[data.commentindex])
      localStorage.setItem('infofo',commentList0)

      */
      localStorage.setItem('infofo',JSON.stringify(data))
      localStorage.setItem('isLike',data.isLike)
      this.$router.push({
        path: "/disdetail",
        query: {
          circleDiscussId: data.id,
          circleId: data.circleId,
          userId: data.userId,
          // index: data.commentindex,
          commentid:data.id
        }
      });
    },
    //获取跳转前的位置
    getTransformState() {
      let loadmore = document.getElementsByClassName("loadmore-ul");
      if (loadmore.length > 0) {
        localStorage.turnBackSay = loadmore[0].style.transform;
      }
    },
    init(){
      this.initDiscuss().then(()=>{
        return this.initScroll()
      }).then(()=>{
         this.$nextTick(() => {
            this.myscroll.refresh();
          });
          let loadmore = document.getElementsByClassName("loadmore-ul");
          if (loadmore.length > 0) {
            loadmore[0].style.transform = localStorage.turnBackInit;
          }
            localStorage.turnCount = "";
             this.myscroll.refresh();
      })
      .then(res => {
        setTimeout(()=>{
          if (!this.scroll) {
            this.scroll = new BScroll(this.$refs.menuWrap, {
              scrollX: true,
              click: true
            })
          } else {
            this.scroll.refresh()
          }
        },20)
      });
    },
    touchmove(e){
      this.moveX = e.touches[0].clientX
      console.log(this.moveX)
      if(this.moveX>0){
        this.moveX = -this.moveX
      }
      this.$refs.overStack.style.left= this.moveX+'px'
    },
    initDiscuss() {
      let p = new Promise((resolve, reject) => {
        const data = {
            page: this.mypage,
            limit: 10,
            sort:1
          };
          api.queryDiscussAll(data).then(res => {
            if (res.success) {
              Indicator.close();
              resolve("获取得到数据...");
              this.commentlist = this.loadmore
                ? [...this.commentlist, ...res.page.list]
                : res.page.list; //res.data.list
              // this.$util.getListUrl(this.commentlist);
             this.totalPage = res.page.totalPage;
              if (res.page.currPage == res.page.totalPage) {
                this.hasmore = false;
              } else {
                this.hasmore = true;
              }
              this.is_r = false;
              if (this.mypage > 1) {
                setTimeout(() => {
                  this.myscroll.refresh();
                }, 0);
              }

              let sayObj = JSON.stringify({
                commentlist: this.commentlist,
                totalPage: this.totalPage,
                hasmore: this.hasmore,
                pageone: this.pageone,
                pagetwo: this.pagetwo,
                mypage: this.mypage,
              });
              localStorage.sayStorage = sayObj;
            }else{
              resolve("获取说说数据失败...");
            }
          });
      })
      return p
    },
    getsayslist() {
      const data = {
        page: this.mypage,
        limit: 10,
        sort: 1
      };
      api.queryDiscussAll(data).then(res => {
        if (res.success) {
          console.log(res.data)
          this.commentlist = this.loadmore
            ? [...this.commentlist, ...res.data.list]
            : res.data.list; //res.data.list
          this.totalPage = res.data.totalPage;
          if (res.data.currPage == res.data.totalPage) {
            this.hasmore = false;
          } else {
            this.hasmore = true;
          }
          this.is_r = false;
          if (this.mypage > 1) {
            setTimeout(() => {
              this.myscroll.refresh();
            }, 0);
          }

          let sayObj = JSON.stringify({
            commentlist: this.commentlist,
            totalPage: this.totalPage,
            hasmore: this.hasmore,
            pageone: this.pageone,
            pagetwo: this.pagetwo,
            mypage: this.mypage,
          });
          localStorage.sayStorage = sayObj;
        }
      });
    },

    initScroll() {
      let p = new Promise((resolve, reject) => {
        let sayWrapper = this.$refs.sayWrapper;
        this.$nextTick(() => {
          this.setScroll(sayWrapper, this);
          resolve("初始化scroll结束...");
        });
      });
      return p;
    },
    setScroll(sayWrapper, _this) {
      localStorage.tempPageHeight = document.getElementsByClassName(
        "loadmore-ul"
      )[0].scrollHeight;
      _this.myscroll = new iScroll(sayWrapper, {
      //   onBeforeScrollStart: function ( e ) {
      //       if ( this.absDistX > (this.absDistY + 5 ) ) {
      //           e.preventDefault();
      //       }
      //   },
      // //解决第一次无法滑动的问题
      // onTouchEnd: function () {
      //   var self = this;
      //   if (self.touchEndTimeId) {
      //     clearTimeout(self.touchEndTimeId);
      //   }

      //   self.touchEndTimeId = setTimeout(function () {
      //     self.absDistX = 0;
      //     self.absDistX = 0;
      //   }, 50);
      // },
        //上拉时触发
        onScrollMove: function() {
          if (
            this.y <= this.wrapperH - this.scroller.clientHeight - 50
            && _this.is_r == false
          ) {
            //加载数据
            _this.is_r = true;
            _this.loadmore = true;
            if (_this.mypage < _this.totalPage) {
                _this.mypage += 1
                _this.initDiscuss();
            }
          }
        },
        onScrollEnd: function() { },
        onScrollStart: function() {
          this.refresh()
        }
      });
      Indicator.close();
    },
    tosaycomdet(data) {
      localStorage.turnCount = "detail2say";
      // this.getTransformState();

      /*this.$router.push({
        path: "/disdetail",
        query: {
          saysId: this.commentlist[data.commentindex].saysId,
          userId: this.commentlist[data.commentindex].userId,
          index: data.commentindex
        }
      });*/
    },
    queryDiscovery(){
              const data = {
                  page: this.page,
                  limit:10,
              }
              api.queryDiscoveryjoin(data).then(res => {
                  if(res.success){
                    if(res.data.length < 2){
                      this.$router.push({path:'/discoveryClub'})
                    }
                      this.list = this.is_r
                     ? [...this.list, ...res.data]
                     : res.data;
                     if(this.list.length==0){
                         this.listnodata = true;
                     } else{
                       this.listnodata = false;
                     }
                     if(this.myscroll){
                       this.$nextTick(() => {
                         this.myscroll.refresh();
                       });
                     }
                  }
              })


    },

   /* //获取跳转前的位置
    getTransformState() {
      let loadmore = document.getElementsByClassName("loadmore-ul");
      if (loadmore.length > 0) {
        localStorage.turnBackDiscovery = loadmore[0].style.transform;
      }
    }*/
  }
}
</script>
<style lang="less" scoped>
.modal-img{
  width: 100%;
  height: 100%;
  background: rgba(0,0,0,.5);
  position: fixed;
  top:0;
  left: 0;
  z-index: 9999;
  img{
    width: 80%;
    position: absolute;
    top:50%;
    left: 10%;
    transform: translateY(-50%);
  }
}
.fade-enter-active, .fade-leave-active {
  transition: opacity .5s;
}
.fade-enter, .fade-leave-to /* .fade-leave-active below version 2.1.8 */ {
  opacity: 0;
}
  .mint-popup{
    width: 100%;
    height: 100%;
    background: transparent;
    position: relative;
  }
  .mint-popup img{
    width: 60%;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: -1;
  }
  .myquanzi{
    height: 2.62rem;
    overflow: hidden;
    background-color: #fff;
    margin-bottom: .2rem;
  }
  .toptitle{
    position: relative;
    height:1rem;
    padding: 0 .4rem;
  }
  .toptitle p{
    line-height: 1rem;
    font-size: .32rem;
    font-weight:500;
    color:#333;
  }
  .findquanzi{
    position: absolute;
    top:0;
    right:.4rem;
    z-index: 1;
    color:#999;
    font-size: .24rem;
    line-height: 1rem;
    font-weight:400;
  }
  .menuContainer{
    overflow: hidden;
  }
  .quanList{
    /* width: 100%; */
    height: 1.26rem;
    padding: 0 .4rem;
    display: inline;
    overflow-x:auto;
    overflow-y:hidden;
    white-space: nowrap;
    float:left;
  }
  .quanList::-webkit-scrollbar {
    display: none;
  }
  .quanList li{
    vertical-align: top;
    width:1.8rem ;
    height: 1.26rem;
    display: inline-block;
    /*background-color: #FB695B;*/
    border-radius: 0 .4rem 0 .4rem;
    margin-right: .2rem;
    overflow: hidden;
    position: relative;
  }
  .quanList li img{
    width:100%;
    height: 100%;
  }
  .quanList li p{
    position: absolute;
    bottom: .16rem;
    text-align: center;
    width: 100%;
    font-weight: 500;
    left: 0;
    z-index: 2;
    font-size: .24rem;
    color: #fff;
  }
.img-with-text{
    background: #ffffff;
    position: relative;
    margin-bottom: 0.28rem;
    width: 3.35rem;
    height: 3.1rem;
    border-radius: 0.1rem;
}
.imgtextback{
  width: 100%;
  height: 1.67rem;
  border-radius: 0.1rem 0.1rem 0 0;
}
.img-with-text p{
  margin: 0;
}
.topiclisttitle{
  font-size: 0.24rem;
  color: #333;
  padding: 0.07rem 0.2rem 0.1rem 0.2rem;
  font-family: PingFangSC Medium;
  line-height: 0.36rem;
  overflow:hidden;
  text-overflow:ellipsis;
  display:-webkit-box;
  -webkit-box-orient:vertical;
  -webkit-line-clamp:2;
}

.topiclistfollownumber{
  font-size: 0.24rem;
  color: #999999;
}
 .hottopictitle {
  font-size: 0.24rem;
  color: #333;
  width: 1.88rem;
  height: 0.44rem;
  line-height: 0.44rem;
  position: absolute;
  top: 0.3rem;
}
.indexhottuati{
  display: flex;
  align-items: center;
  justify-content: center
}
.dicoveryul{
    display: flex;
    flex-wrap: wrap;
    list-style: none;
    padding: 0;
    align-content: flex-start;
}
.dicoveryul li{
    padding-left: 0.28rem;
}
.follownumbase{
    display: flex;
    align-items: center;
    position: absolute;
    bottom: 0.2rem;
    padding:0 0.2rem;
}
.follownumicon{
    font-size: 0.26rem;
    color: #999999;
}
.all-hot-title {
  background: #f5f5f5;
  height: 0.8rem;
  padding:0.02rem 0 0 0.3rem;
  font-size: 0.3rem;
  display: flex;
  align-items: center;
  font-family: "PingFangSC Regular";
  color: #3a3a3a;
}
.discoverylabel{
  background-color: rgba(0,0,0,0.3);
  position: absolute;
  top: 0.16rem;
  left: 0.16rem;
  color: #ffffff;
  font-size: 0.22rem;
  border-radius:0.22rem;
}
.discoverylabel div{
  padding: 0.02rem 0.15rem;
}
.contanier{
  position: relative;
}
  .loadmore-container {
    overflow: hidden;
    height: 95vh;
    margin: 0 auto;
    position: relative;
  }

  .loadmore-ul {
    padding-bottom: 1.2rem;
    list-style: none;
    
  }
  .loadmore-ul li:last-child{
      margin-bottom:1rem
    }
</style>

